package cn.kgc.chlm.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


public class JdbcUtil {

	//当前线程对象。
	private static ThreadLocal<Connection> threadLocal;
	
	private static DataSource ds;
	
	private static Connection conn;
	
	static {
		//实例化ThreadLocal对象
		threadLocal = new ThreadLocal<>();
		//prpperties对象，用于读取配置文件信息
		Properties prop = new Properties();
		//通过当前类的类加载器，读取配置文件按到一个输入流中
//		InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
		InputStream is = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");

		try {
			//properties对象，加载输入流
			System.out.println(is);
			prop.load(is);
			//Druid数据源加载Properties对象，生成数据源对象
			ds = DruidDataSourceFactory.createDataSource(prop);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 *
	 * @return 数据源
	 */
	public static DataSource getDataSource() {

		return ds;
	}

	/**
	 *
	 * @return 返回连接
	 */
	public static  Connection getConnection() {

		//从当前线程中获取连接对象
		conn = threadLocal.get();

		try {
			//没有conn为空
			if(conn == null){
				//通过数据源，获取Connnection对象。
				conn = ds.getConnection();
				//存入到线程
				threadLocal.set(conn);
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//返回连接
		return conn;
	}
	
}
